package com.java2.ObjectOutput;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.entity.Person;

/**
 * {@link Person ttext}
 * @see Person
 * {@code Person}
 * @since 2017/6/14
 * @author Administrator
 * 
 */
public class ObjectOutput {
	public static void main(String[] args) {
		List<Person> list = initData();
		String path = "C:" + File.separator;
		String fileName = "zzzobj.txt";

		try {
			ObjoutPut(list, path, fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ObjInput(path, fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void ObjInput(String path, String fileName)
			throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream inputStream = new ObjectInputStream(
				new FileInputStream(new File(path, fileName)));

		List<Person> list = (List<Person>) inputStream.readObject();
		for (Person person : list) {
			System.out.println(person);

		}

	}

	private static void ObjoutPut(List<Person> list, String path,
			String fileName) throws FileNotFoundException, IOException {

		ObjectOutputStream outputStream = new ObjectOutputStream(
				new FileOutputStream(new File(path, fileName)));
		outputStream.writeObject(list);
		outputStream.flush();
		outputStream.close();
	}

	private static List<Person> initData() {
		List<Person> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			Person p = new Person("name:tom" + i, i + 10);
			list.add(p);
		}
		return list;

	}

}
